package com.woniuxy.opencv.service.impl;

import com.baidu.aip.ocr.AipOcr;
import com.woniuxy.opencv.service.LicensePlateService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import java.util.Base64;
import java.util.HashMap;

@Slf4j
@Service
public class LicensePlateServiceImpl implements LicensePlateService {

    @Autowired
    private AipOcr aipOcr;

    @Override
    public String recognizeLicensePlate(String base64Image) {
        try {
            // 解码Base64数据
            byte[] imageBytes = Base64.getDecoder().decode(base64Image);
            
            // 调用百度OCR API
            JSONObject res = aipOcr.plateLicense(imageBytes, new HashMap<>());
            log.info("OCR识别结果：{}", res.toString());

            if (res.has("words_result")) {
                JSONObject result = res.getJSONObject("words_result");
                String number = result.getString("number");
                log.info("成功识别车牌号：{}", number);
                return number;
            }
            return "未识别到车牌";
        } catch (Exception e) {
            log.error("车牌识别过程发生异常", e);
            return "识别失败：" + e.getMessage();
        }
    }
} 